package com.skyline.jfs.namespace.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.skyline.jfs.namespace.dao.JFSDirectoryDao;
import com.skyline.jfs.namespace.dao.JFSFileDao;
import com.skyline.jfs.namespace.model.JFSDirectory;
import com.skyline.jfs.namespace.model.JFSFile;
import com.skyline.jfs.namespace.model.JFSLsResult;
import com.skyline.jfs.namespace.service.JFSDirectoryService;

@Service("jfsDirectoryService")
public class JFSDirectoryServiceImpl implements JFSDirectoryService {

	@Autowired
	private JFSDirectoryDao jfsDirectoryDao;
	
	@Autowired 
	private JFSFileDao jfsFileDao;

	public List<JFSDirectory> lsDir(Long id) {
		return jfsDirectoryDao.findAllSubDirsById(id);
	}

	public List<JFSFile> lsFile(Long id) {
		return jfsFileDao.findAllSubFiles(id);
	}
	
	public JFSLsResult ls(Long id) {
		JFSLsResult result = new JFSLsResult();
		List<JFSDirectory> dirs = lsDir(id);
		List<JFSFile> files = lsFile(id);
		JFSDirectory currentDir = get(id);
		if (dirs != null) {
			result.setDirs(dirs);
		}
		if (files != null) {
			result.setFiles(files);
		}
		if (currentDir != null) {
			result.setCurrentDir(currentDir);
		}
		return result;
	}

	public JFSLsResult ls(String dir) {
		if (dir == null||dir.equals("")) {
			dir = "/";
		} else if (dir.substring(dir.length() - 1, dir.length()).equals("/") == false) {
			dir = dir + "/";
		}
		JFSLsResult result = new JFSLsResult();
		JFSDirectory jfsDir = get(dir);
		if (jfsDir != null) {
			List<JFSDirectory> dirs = lsDir(jfsDir.getId());
			List<JFSFile> files = lsFile(jfsDir.getId());
			// JFSDirectory currentDir = get(dir);
			if (dirs != null) {
				result.setDirs(dirs);
			}
			if (files != null) {
				result.setFiles(files);
			}
			if (jfsDir != null) {
				result.setCurrentDir(jfsDir);
			}
		}
		return result;
	}

	public void createDir(Long parent, String path, String name,
			Integer permission) {
		jfsDirectoryDao.insertDir(parent, path, name, permission);
	}

	public void createDir(String dir) {
		// TODO Auto-generated method stub

	}

	public void rm(Long id) {
		// TODO Auto-generated method stub

	}

	public void rm(String dir) {
		// TODO Auto-generated method stub

	}

	public void modify(String dir) {
		// TODO Auto-generated method stub

	}

	public void rename(Long id, String newName) {
		// TODO Auto-generated method stub

	}

	public void rename(String dir, String newName) {
		// TODO Auto-generated method stub

	}

	public JFSDirectory get(Long id) {
		return jfsDirectoryDao.findDirByID(id);
	}

	public JFSDirectory get(String dir) {
		return jfsDirectoryDao.findDirByDir(dir);
	}
}
